#encoding=utf8
from django.contrib.auth import *
from django.contrib.auth.models import *
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db import transaction
from django.forms.models import model_to_dict
from django.http import *
from django.shortcuts import *
from django.views.decorators.http import require_http_methods, require_POST, \
    require_GET
import json
import uuid

from trp.models import *
from utils.JsonResponse import JsonResponse, JsonResponseBadrequest
from utils.decorators import *
from utils.utils import *
from website.settings import LOGGER as logger
from trp.views.cost import get_current_balance

CHARGE_SEQUENCE="charge_seq"
@login_required
def main(request):
    org_id=-1
    if not request.GET:
        org_id = -1 
    else :
        org_id=request.GET.get("org_id",-1)
    org = None
    try :
        org = Organization.objects.get(pk=int(org_id),deleted=False)
    except :
        pass
    seq = _charge_seq(request)
    return render_to_response('trp/user.html', {'user' : request.user, 'page' : 'organization','org_id':org_id,"organization":model_to_dict(org),"charge_seq":seq})

@login_required_ajax
@require_POST
@transaction.atomic
def do_modify(request):
    param = json.loads(request.body)
    try :
        with transaction.atomic():
            account_login = request.user.account
            username = param.get("name")
            account = User.objects.get(username=username).account
            if account.deleted :
                raise Exception("user had been deleted")
            phone = str(param.get("phone") or "")
            email = str(param.get("email") or "")
            description = (param.get("description")or "").encode("utf-8") 
            old_phone=str(account.phone)
            old_email=str(account.user.email)
            old_desc=account.description.encode("utf-8")
            
            if account_login.is_admin() :
                account.description = description
            elif account_login.id != account.id :
                account.description = description 
                
    #         if username and username !=account.user.username and Account.objects.filter(user__username=username,deleted=False).exsits():
    #             account.username = username
            account.phone = phone
            account.user.email = email
            account.user.save()
            account.save()
            
            details=""
            if cmp(old_phone,phone):
                details+="手机:"+phone+";"
            if cmp(old_email,email):
                details+="邮箱:"+email+";"
            if cmp(old_desc,description):
                details+="描述:"+description+";"    
            operation_log=OperationLog()
            operation_log.operation="修改"
            operation_log.object="用户"
            operation_log.user=request.user
            operation_log.details=details      
            operation_log.object_id=account.user.id 
            operation_log.save()
    except Exception,e:
        logger.exception(e)
        return JsonResponseBadrequest({"message":"bad request"})

    return JsonResponse({"message":"ok"})

@login_required_ajax
@require_POST
@transaction.atomic
def reset_password(request):
    params = json.loads(request.body)
    userId=params.get("user_id")
    password=params.get("password")
    password_new=params.get("password_confirm")
    password_old = params.get("password_old")
    user_reset = None
    try :
        with transaction.atomic():
            user_reset = Account.objects.get(pk=int(userId),deleted=False)
            if (password_new != password):
                raise Exception("两次输入的密码不一致")
    #         修改自己的密码
            if request.user.account.id ==int(userId) :
                if request.user.account.is_admin():
                    if password_old :
    #                     管理员验证原密码
                        if request.user.check_password(password_old) :
                            __reset_password(request.user, password)
                        else :
                            raise Exception("原密码错误") 
                    else :
    #                     管理员重置密码
                        __reset_password(request.user, password)
                else :
    #                 非管理员修改密码
                    if request.user.check_password(password_old) :
                            __reset_password(request.user, password)
                    else :
                        raise Exception("原密码错误") 
    #         管理员重置别人的密码
            elif request.user.account.is_admin():
                __reset_password(user_reset.user, password)
            else :
                raise Exception("对不起，您无权修改他人密码")
            operation_log=OperationLog()
            operation_log.operation="重置密码"
            operation_log.object="用户"
            operation_log.user=request.user            
            operation_log.object_id=int(userId)
            operation_log.save()
    except Exception,e:
        logger.exception(e)
        return JsonResponseBadrequest({"message":str(e)})
    return JsonResponse({"message":"ok"})

def __reset_password(user,password):
    user.set_password(password)
    user.save()

@login_required
@require_http_methods(["DELETE"])
def do_delete(request):
#     TODO 这期没删除
    return HttpResponseBadRequest("bad request")

@login_required_ajax
@require_POST
@transaction.atomic
def do_create(request):
    param = json.loads(request.body)
    username = param.get("name","")
    orgs = param.get("org_id")
    email = param.get("email","")
    phone = param.get("phone","")
    description = param.get("description","")
    password = param.get("password")
    password_confirm=param.get("password_confirm")
#     1 运营人员 2 管理员
    user_type = param.get("type",1) or 1
    try :
        with transaction.atomic():
            if not request.user.account.is_admin():
                raise Exception("no auth")
    
            if not password or password!=password_confirm :
                raise Exception("password is illegal")
    
            if not username or Account.objects.filter(user__username=username,deleted=False).exists():
                raise Exception("user name is illegal")
    
            if not orgs:
                raise Exception("org can not be empty")
    
            orgIds = split_to_int_array(orgs)
            organizations = Organization.objects.filter(id__in=orgIds)
            
            if not organizations :
                raise Exception("org is illegal")
    
            org = organizations[0]
            admin = False
            if int(user_type) == 2 :
                admin =True
            if org.type !=OrgType.PLATFORM :
                admin =False 
    
            u = User(username=username,email=email)
            u.set_password(password)
            u.save()
            account = Account(user=u,phone=phone,description = description,admin=admin)
            account.save()
            account.organization= organizations
            
            details="用户名:"+username.encode("utf-8")+";"+"手机:"+phone.encode("utf-8")+";"+"邮箱:"+email.encode("utf-8")+";"+"描述:"+description.encode("utf-8")+";"
            operation_log=OperationLog()
            operation_log.operation="新建"
            operation_log.object="用户"
            operation_log.user=request.user
            operation_log.details=details      
            operation_log.object_id=account.id 
            operation_log.save()

    except Exception,e:
        logger.exception(e)
        return JsonResponseBadrequest({"message":str(e)})
    return JsonResponse({"message":"ok"})

@login_required_ajax
@require_GET
def get_user(request):
    u={}
    uid =request.GET.get("userId",-1)
    account_login  = request.user.account
    try:
        account = Account.objects.prefetch_related("organization").get(pk=int(uid),deleted=False)
        org  = account.organization.all()[0]
        u["id"]=account.id
        u["username"]=account.user.username
        u["phone"]=account.phone
        u["email"]=account.user.email
        if org.type==OrgType.PLATFORM:
            u['type']=account.admin and "2" or "1"
        else :
            u['type']=''
        if account.is_admin() or account_login.id != int(uid):
            u["description"]=account.description
    except Exception,e:
        logger.exception(e)
        return JsonResponseBadrequest({"message":str(e)})
    return JsonResponse(u)

@login_required_ajax
@require_POST
def get_users(request):
    result = {}
    dataArr =[]
    req={}
    try :
        req = json.loads(request.body)
    except Exception,e:
        logger.exception(e)
        return JsonResponseBadrequest({"message":"bad request"})
    searchTxt = req.get("search_text")
    pageNo= req.get('pageNo',1)
    pageSize = req.get("pageSize",20)
    orderBy = req.get("orderBy","id")
    order = req.get("order","desc")
    orgId = int(req.get("org_id",-10))

    if orderBy :
        orderBy = (order =="asc" and "" or "-") + orderBy
    org = None
    count = 0
    try :
        try:
            org = Organization.objects.get(pk=int(orgId),deleted=False)
        except:
            raise Exception("组织不存在!")
        datalist=get_current_balance([orgId],False)
        data=datalist[0]
        if data.get("in_balance"):
            result["in_balance"]=data["in_balance"]
            result["out_balance"]=data["out_balance"]
            result["ally_balance"]=data["ally_balance"]
        else:
            raise Exception("业务服务器异常")
        
        orgUsers = org.account_set.all().select_related().filter(deleted=False)
        if searchTxt :
            orgUsers = orgUsers.filter(user__username__icontains=searchTxt)
        if orderBy :
            orgUsers = orgUsers.order_by(orderBy)
        paginator = Paginator(orgUsers, pageSize)
        count =paginator.count
        try:
            pageObj = paginator.page(int(pageNo))
        except PageNotAnInteger:
            pageObj = paginator.page(1)
        except EmptyPage:
            pageObj = paginator.page(paginator.num_pages)
        for e in pageObj.object_list:
            u ={}
            u["id"]=e.id
            u["username"]=e.user.username
            u["phone"]=e.phone
            u["email"]=e.user.email
            #     1 运营人员 2 管理员
            if org.type==OrgType.PLATFORM:
                u['type']=e.admin and "2" or "1"
            else :
                u['type']=''
            u["description"]=e.description
            dataArr.append(u)
        result["bodyData"]=dataArr
        result["pageSize"]=pageSize
        result["pageNo"]=pageNo
        result["totalCount"]=count
    except Exception,e:
        logger.exception(e)        
        return JsonResponseBadrequest({'message':str(e)})
    return JsonResponse(result)

@login_required_ajax
@require_POST
def check_username(request):    
    param = json.loads(request.body)
    username=str(param.get("username",""))
    username=username.strip()   
    if not username :
        return HttpResponseBadRequest()
    flag = Account.objects.filter(user__username=username,deleted=False).exists()
    if flag :
        return JsonResponse({"message":"ok"})
    return JsonResponseBadrequest({"message":"fail"})

def _charge_seq(request):
    seq = uuid.uuid4().hex
    request.session[CHARGE_SEQUENCE] = seq
    return seq
@login_required_ajax
def get_system_time(request):
    result={}
    result["time"]=datetime.datetime.now().strftime("%Y-%m-%d")
    return JsonResponse(result)
    